from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import User, db
from utils import hash_password, format_response
from decorators import admin_required
import traceback

teachers_bp = Blueprint('teachers', __name__)

@teachers_bp.route('/', methods=['GET', 'OPTIONS'])
@jwt_required()
@admin_required
def get_teachers():
    """获取教师列表"""
    try:
        teachers = User.query.filter_by(role='teacher').all()
        teacher_list = []
        
        for teacher in teachers:
            teacher_data = teacher.to_dict()
            # 这里可以添加课程权限信息
            teacher_data['course_permissions'] = []  # 暂时为空，后续可以添加课程权限关联
            teacher_list.append(teacher_data)
        
        return jsonify(format_response(teacher_list))
        
    except Exception as e:
        print(f"获取教师列表错误: {str(e)}")
        print(f"错误详情: {traceback.format_exc()}")
        return jsonify(format_response(message=str(e), code=500)), 500

@teachers_bp.route('/', methods=['POST', 'OPTIONS'])
@jwt_required()
@admin_required
def add_teacher():
    """添加教师账号"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        name = data.get('name', '')
        email = data.get('email', '')
        course_ids = data.get('courseIds', [])
        
        if not username or not password:
            return jsonify(format_response(message="用户名和密码不能为空", code=400)), 400
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=username).first():
            return jsonify(format_response(message="用户名已存在", code=400)), 400
        
        # 创建新教师用户
        hashed_password = hash_password(password)
        new_teacher = User(
            username=username,
            password=hashed_password,
            name=name,
            email=email,
            role='teacher'
        )
        db.session.add(new_teacher)
        db.session.commit()
        
        # 这里可以添加课程权限关联逻辑
        # 暂时跳过，后续实现
        
        return jsonify(format_response(new_teacher.to_dict(), "教师账号添加成功"))
        
    except Exception as e:
        db.session.rollback()
        print(f"添加教师错误: {str(e)}")
        print(f"错误详情: {traceback.format_exc()}")
        return jsonify(format_response(message=str(e), code=500)), 500

@teachers_bp.route('/batch', methods=['POST', 'OPTIONS'])
@jwt_required()
@admin_required
def batch_add_teachers():
    """批量添加教师账号"""
    try:
        data = request.get_json()
        teachers_data = data.get('teachers', [])
        
        if not teachers_data or not isinstance(teachers_data, list):
            return jsonify(format_response(message="教师数据格式错误", code=400)), 400
        
        if len(teachers_data) > 50:  # 限制批量添加数量
            return jsonify(format_response(message="批量添加数量不能超过50个", code=400)), 400
        
        success_count = 0
        failed_teachers = []
        
        for teacher_data in teachers_data:
            try:
                username = teacher_data.get('username')
                password = teacher_data.get('password', 'teacher123')
                name = teacher_data.get('name', '')
                email = teacher_data.get('email', '')
                
                if not username or not name:
                    failed_teachers.append({
                        'username': username,
                        'name': name,
                        'error': '用户名和姓名不能为空'
                    })
                    continue
                
                # 检查用户名是否已存在
                if User.query.filter_by(username=username).first():
                    failed_teachers.append({
                        'username': username,
                        'name': name,
                        'error': '用户名已存在'
                    })
                    continue
                
                # 创建新教师用户
                hashed_password = hash_password(password)
                new_teacher = User(
                    username=username,
                    password=hashed_password,
                    name=name,
                    email=email,
                    role='teacher'
                )
                db.session.add(new_teacher)
                success_count += 1
                
            except Exception as e:
                failed_teachers.append({
                    'username': username if 'username' in locals() else 'unknown',
                    'name': name if 'name' in locals() else 'unknown',
                    'error': str(e)
                })
        
        db.session.commit()
        
        return jsonify(format_response({
            'success_count': success_count,
            'failed_count': len(failed_teachers),
            'failed_teachers': failed_teachers
        }, f"批量添加完成，成功{success_count}个，失败{len(failed_teachers)}个"))
        
    except Exception as e:
        db.session.rollback()
        print(f"批量添加教师错误: {str(e)}")
        print(f"错误详情: {traceback.format_exc()}")
        return jsonify(format_response(message=str(e), code=500)), 500

@teachers_bp.route('/<int:teacher_id>', methods=['PUT', 'OPTIONS'])
@jwt_required()
@admin_required
def update_teacher(teacher_id):
    """更新教师信息"""
    try:
        teacher = User.query.filter_by(id=teacher_id, role='teacher').first()
        if not teacher:
            return jsonify(format_response(message="教师不存在", code=404)), 404
        
        data = request.get_json()
        name = data.get('name')
        email = data.get('email')
        status = data.get('status')
        
        if name is not None:
            teacher.name = name
        if email is not None:
            teacher.email = email
        if status is not None:
            teacher.status = status
        
        db.session.commit()
        
        return jsonify(format_response(teacher.to_dict(), "教师信息更新成功"))
        
    except Exception as e:
        db.session.rollback()
        print(f"更新教师信息错误: {str(e)}")
        print(f"错误详情: {traceback.format_exc()}")
        return jsonify(format_response(message=str(e), code=500)), 500

@teachers_bp.route('/<int:teacher_id>/permissions', methods=['PUT', 'OPTIONS'])
@jwt_required()
@admin_required
def update_teacher_permissions(teacher_id):
    """更新教师课程权限"""
    try:
        teacher = User.query.filter_by(id=teacher_id, role='teacher').first()
        if not teacher:
            return jsonify(format_response(message="教师不存在", code=404)), 404
        
        data = request.get_json()
        course_ids = data.get('courseIds', [])
        
        # 这里可以添加课程权限更新逻辑
        # 暂时跳过，后续实现
        
        return jsonify(format_response(message="教师权限更新成功"))
        
    except Exception as e:
        db.session.rollback()
        print(f"更新教师权限错误: {str(e)}")
        print(f"错误详情: {traceback.format_exc()}")
        return jsonify(format_response(message=str(e), code=500)), 500

@teachers_bp.route('/<int:teacher_id>', methods=['DELETE', 'OPTIONS'])
@jwt_required()
@admin_required
def delete_teacher(teacher_id):
    """删除教师账号"""
    try:
        teacher = User.query.filter_by(id=teacher_id, role='teacher').first()
        if not teacher:
            return jsonify(format_response(message="教师不存在", code=404)), 404
        
        # 检查是否有相关的班级或作业
        # 这里可以添加检查逻辑，防止删除有相关数据的教师
        
        db.session.delete(teacher)
        db.session.commit()
        
        return jsonify(format_response(message="教师账号删除成功"))
        
    except Exception as e:
        db.session.rollback()
        print(f"删除教师错误: {str(e)}")
        print(f"错误详情: {traceback.format_exc()}")
        return jsonify(format_response(message=str(e), code=500)), 500
